package com.ruoyi.common.core.utils;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.GeoOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class GeoUtil implements InitializingBean {

    @Autowired
    private RedisTemplate<String,String> stringRedisTemplate;


    private static RedisTemplate<String,String> redisTemplate;

    private static final String GEO_KEY = "DISTANCE";

    /**
     * 将经纬度信息添加到redis中
     * @param certId 标识
     * @param longitude 经度
     * @param latitude 纬度
     */
    public static void geoAdd(String certId, double longitude, double latitude) {
        GeoOperations geoOperations = redisTemplate.opsForGeo();
        Point point = new Point(longitude, latitude);
        RedisGeoCommands.GeoLocation geoLocation = new RedisGeoCommands.GeoLocation(certId, point);
        geoOperations.add(GEO_KEY, geoLocation);
    }

    /**
     * 两个人之间的距离
     * @param certId1
     * @param certId2
     * @return
     */
    public static  long distanceBetween(String certId1, String certId2) {
        GeoOperations geoOperations = redisTemplate.opsForGeo();
        Distance distance = geoOperations.distance(GEO_KEY, certId1, certId2);
        return Math.round(distance.getValue());
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        redisTemplate=this.stringRedisTemplate;
    }
}
